#!/bin/sh
exec >>/var/log/host-config.log

date

d=$(date '+%s')

if ! curl -sLIf git.apiote.xyz >/dev/null
then
  echo 'git.apiote.xyz is not available; exiting'
  exit
fi

echo 'pulling changes'
git stash
git pull

if [ "$(stat -c '%Y' /usr/share/secrets/secrets.tar.age)" -gt "$d" ]
then
  echo 'secrets are new; notifying'
  # TODO probably send email
  # # shellcheck disable=SC2016
  # notify-send 'Host-Config' 'There are new secrets. Decrypt using `secrets decrypt`'
fi

if [ "$(stat -c '%Y' /etc/apk/world)" -gt "$d" ]
then
  echo 'world is new; fixing'
  apk fix
fi

if [ "$(stat -c '%Y' /etc/network/interfaces)" -gt "$d" ]
then
  echo 'interfaces is new; restarting network'
  /etc/init.d/network restart
fi

for service in $(find /etc/conf.d | grep -v 'apk.new')
do
  serviceName=$(basename "$service")
  if [ "$(stat -c '%Y' "$service")" -gt "$d" ] && (rc-update show | grep -e default -e boot | cut -d '|' -f 1 | tr -d ' ' | grep -q "$serviceName")
  then
    echo "config for $serviceName is new; restarting"
   "/etc/init.d/$serviceName" restart
  fi
done
for service in $(find /etc/init.d | grep -v 'apk.new')
do
  serviceName=$(basename "$service")
  if [ "$(stat -c '%Y' "$service")" -gt "$d" ] && (rc-update show | grep -e default -e boot | cut -d '|' -f 1 | tr -d ' ' | grep -q "$serviceName")
  then
    echo "init script for $serviceName is new; restarting"
   "/etc/init.d/$serviceName" restart
  fi
done